package org.ting.book.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.ting.book.component.ResultFail;
import org.ting.book.component.ResultGenerator;
import org.ting.book.component.ResultSuccess;
import org.ting.book.model.BookInfo;
import org.ting.book.model.Result;
import org.ting.book.service.BookService;

import java.util.List;

@RestController
@RequestMapping("/book")
public class BookController {
    //对象组合 todo
    @Autowired
    BookService bookService;
    ResultGenerator success = new ResultSuccess();
    ResultGenerator fail = new ResultFail();
    @RequestMapping("/getBookList")
    public List<BookInfo> getBookList() {
        List<BookInfo> result = bookService.getBookList();
        //赋值statusName
        for(BookInfo book : result) {
            if(book.getStatus()) {
                book.setStatusName("可借阅");
            }else {
                book.setStatusName("不可借阅");
            }

        }
        return result;
    }

    //对象参数传递 todo
    @RequestMapping("/insert")
    public Result<?> insertBook(BookInfo book) {
        if(book.getBookName().equals("") || book.getAuthor().equals("") || book.getPublish().equals("") || book.getStatus() == null) {
            return fail.getResult("请输入完整的图书信息");
        }
        if(book.getTotal() <= 0) {
            return fail.getResult("图书数量必须大于0");
        }
        if(book.getPrice() < 0) {
            return fail.getResult("图书价格必须大于等于0");
        }
        //处理count的值初始为total
        book.setCount(book.getTotal());

        return bookService.insertBook(book);
    }

    @RequestMapping("/delete")
    public Result<?> deleteBook(Integer bookId) {
        return bookService.deleteBookById(bookId);
    }

    @RequestMapping("/getBookById")
    public BookInfo getBookById(Integer bookId) {
        return bookService.getBookById(bookId);
    }

    @RequestMapping("/update")
    public Result<?> updateBook(BookInfo book) {
        if(book.getBookName().equals("") || book.getAuthor().equals("") || book.getPublish().equals("") || book.getStatus() == null) {
            return fail.getResult("请输入完整的图书信息");
        }
        if(book.getCount() <= 0) {
            return fail.getResult("数量必须大于0");
        }

        return bookService.updateBook(book);
    }
}
